const app = getApp()
import util from '../../../utils/util'
import dateTimePicker from '../../../utils/dateTimePicker'
import {
  GetGriderAll,
  GetEventCatList,
  GetEventDetail,
  GetIsseuMembers,
  HandleMemberUpEvent
} from '../../../config/api'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    dateTimeArray: '',
    dateTime: '',

    adminInfo: '',
    id: '',
    ucid: '',
    ucid_name: '',
    status: '', // 事件处理状态
    detail: '',
    event_index: 0,
    eventArr: [{
      title: '本级解决',
      id: 1
    }, {
      title: '直接上报',
      id: 2
    }, {
      title: '指派下级',
      id: 4
    }], // 上报类型数组

    imgs: [],
    count: 0,
    compressImgsSizeArr: [],

    grider_storge: '', // 网格员缓存信息
    content: '',

    showView: true, // 显示弹窗
    showEventView: true, // 显示事件类型弹窗
    event_type_index: '',
    event_typeArr: [], // 事件类型

    isShowNamePopup: false, // 是否显示姓名弹出
    allName: [], // 所有当事人
    uid: '', // 当事人id
    u_name: '', // 当事人名称
    uc_name: '', // 事件类型

    event_level: '',
    event_level_index: 0,
    eventLevelArr: [{
        id: 1,
        title: '普通事件'
      },
      {
        id: 2,
        title: '重点事件'
      }
    ],

    solut: 1,
    isShowReceiver: false, // 是否显示接收人弹层
    receiverArr: [], // 接收人数组
    helper: '', // 接收人id
    helper_name: '', // 接收人姓名
    time: '',

    handle_uid: '',
    handle_name: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log('options', options)
    let adminInfo = wx.getStorageSync('adminInfo')
    let grider_storge = wx.getStorageSync('grider')

    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);

    // {{dateTimeArray[0][dateTime[0]]}}-{{dateTimeArray[1][dateTime[1]]}}-{{dateTimeArray[2][dateTime[2]]}} {{dateTimeArray[3][dateTime[3]]}}:{{dateTimeArray[4][dateTime[4]]}}:{{dateTimeArray[5][dateTime[5]]}}

    var time = obj.dateTimeArray[0][obj.dateTime[0]] + '-' +
      obj.dateTimeArray[1][obj.dateTime[1]] + '-' +
      obj.dateTimeArray[2][obj.dateTime[2]] + ' ' +
      obj.dateTimeArray[3][obj.dateTime[3]] + ':' +
      obj.dateTimeArray[4][obj.dateTime[4]] + ':' +
      obj.dateTimeArray[5][obj.dateTime[5]];

    this.setData({
      grider_storge,
      adminInfo,
      id: options.id,
      status: options.status,
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      time
    })

    this.getEventType(); // 获取事件类型
    this.getDetail();
  },

  changeDateTime(e) { // 选择处理时间
    this.setData({
      dateTime: e.detail.value
    });
    this.setData({
      time: this.data.dateTimeArray[0][this.data.dateTime[0]] + '-' + this.data.dateTimeArray[1][this.data.dateTime[1]] + '-' + this.data.dateTimeArray[2][this.data.dateTime[2]] + " " + this.data.dateTimeArray[3][this.data.dateTime[3]] + ':' + this.data.dateTimeArray[4][this.data.dateTime[4]] + ':' + this.data.dateTimeArray[5][this.data.dateTime[5]]
    })
    console.log("time_nihd", this.data.time);
  },

  changeDateTimeColumn(e) { // 选择处理时间2
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    console.info("dateArr:", dateArr[2]);
    this.setData({
      dateTimeArray: dateArr
    });

    console.log("nihao", this.data.dateTimeArray)
  },

  getGriderAll() { // 获取接收人
    let that = this;
    util.apiRequest(GetGriderAll, {
      vollege_id: app.globalData.vollege_id
    }, null).then(r => {
      console.log('接收人：', r)
      that.setData({
        receiverArr: r.data.data
      })
    })
  },

  onSelectReceiver() { // 选择接收人 / 处理人
    this.getGriderAll() // 调用接收人
    this.setData({
      isShowReceiver: true
    })
  },

  onConfirmReceiver(e) { // 点击确认接收人
    console.log('选择接收人', e)
    let id = e.currentTarget.dataset.id;
    let name = e.currentTarget.dataset.name;

    if (this.data.solut == 1) {
      this.setData({
        handle_uid: id,
        handle_name: name,
        isShowReceiver: false
      })
    } else {
      this.setData({
        helper: id,
        helper_name: name,
        isShowReceiver: false
      })
    }
  },

  bindDateChange: function(e) { // 选择处理时间
    console.log('处理时间：', e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },

  getDetail() {
    let that = this;
    util.apiRequest(GetEventDetail, {
      id: this.data.id
    }, null).then(r => {
      console.log(r)
      that.setData({
        detail: r.data.data,
        uid: r.data.data.uid,
        u_name: r.data.data.u_name,
        uc_name: r.data.data.uc_name,
        ucid: r.data.data.ucid
      })
    })
  },

  bindChangeEventLevel: function(e) {
    console.log('事件等级：', e.detail.value)
    let event_level = this.data.eventLevelArr[e.detail.value]
    this.setData({
      event_level_index: e.detail.value,
      event_level
    })
  },

  getEventType() {
    let that = this;
    util.apiRequest(GetEventCatList, {
      vollege_id: app.globalData.vollege_id
    }).then(r => {
      console.log('事件类型：', r)
      that.setData({
        event_typeArr: r.data.data
      })
    })
  },

  onShowEventPopup() { // 显示事件类型弹层
    this.setData({
      showEventView: false
    })
  },

  onSelectEvent(e) { // 点击选择事件类型
    let event_type_index = e.currentTarget.dataset.event_type_index;
    console.log('事件名称：', this.data.event_typeArr[event_type_index].title)
    console.log('事件id：', this.data.event_typeArr[event_type_index].id)
    this.setData({
      showEventView: true,
      event_type_index: event_type_index,
      uc_name: this.data.event_typeArr[event_type_index].title,
      ucid: this.data.event_typeArr[event_type_index].id
    })
  },

  onSearchName(e) { // 输入搜索当事人
    console.log(e)
    let name = e.detail.value;
    console.log('name', name)
    if (name != '') {
      this.setData({
        isShowNamePopup: true
      })
      util.apiRequest(GetIsseuMembers, {
        id: this.data.grider_storge.id,
        name: name,
        vollege_id: app.globalData.vollege_id
      }, null).then(r => {
        console.log('搜索：', r)
        this.setData({
          allName: r.data.data
        })
      })
    } else {
      this.setData({
        tname: '',
        isShowNamePopup: false
      })
    }
  },

  onConfirmName(e) { // 点击确认当事人
    console.log('选择姓名', e)
    let uid = e.currentTarget.dataset.id;
    let u_name = e.currentTarget.dataset.name;
    this.setData({
      uid,
      u_name,
      isShowNamePopup: false
    })
  },

  // 预览事件内容图片
  previewAttach: function(e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index);
    let imgs = that.data.detail.attach;
    // console.log('imgs', that.data.Imgs);
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  // 预览事件处理图片
  previewReplyImg: function(e) {
    console.log('预览处理图片e:', e)
    let that = this;
    var index = e.currentTarget.dataset.index;
    var pindex = e.currentTarget.dataset.pindex;

    console.log('aa预览index', index);

    let imgs = this.data.detail.handle_log[pindex].attach

    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },

  bindChangeEvent: function(e) { // 选择处理方式
    console.log('处理类型：', e.detail.value)
    let solut = this.data.eventArr[e.detail.value].id
    this.setData({
      event_index: e.detail.value,
      solut,
    })
  },

  // bindChangeLevel(e) {
  //   console.log('预警类型：', e.detail.value)
  //   this.setData({
  //     level_index: e.detail.value
  //   })
  // },

  inputContent(e) {
    // console.log(e.detail.value)
    this.setData({
      content: e.detail.value
    })
  },

  onShowChuli() { // 显示我要处理弹层
    this.setData({
      showView: false
    })
  },

  close: function() { // 关闭弹窗
    let that = this;
    that.setData({
      showView: (!that.data.showView)
    })
  },

  formSubmit() {
    let that = this;

    // if (this.data.uc_name == '') {
    //   wx.showModal({
    //     content: '请选择事件类型',
    //     showCancel: false
    //   })
    //   return;
    // }

    if (this.data.solut == 1) { // 本级处理
      console.log('本级处理')
      if (this.data.handle_uid == '') {
        wx.showModal({
          showCancel: false,
          content: '请选择处理人',
        })
        return;
      }

      let content = this.data.content.replace(/(^\s*)|(\s*$)/g, "");
      if (!content) {
        wx.showModal({
          showCancel: false,
          content: '请填写内容',
        })
        return;
      }
      var params = {
        ucid: this.data.ucid,
        event_id: that.data.id,
        handle_uid: that.data.handle_uid,
        handle_name: that.data.handle_name,
        content: that.data.content,
        attach: that.data.imgs,
        solut: that.data.solut,
        time: that.data.time
      }
    } else if (this.data.solut == 2) {
      console.log('直接上报')
      var params = {
        ucid: this.data.ucid,
        event_id: that.data.id,
        solut: that.data.solut,
      }
    } else {
      console.log('指派下级')
      var params = {
        ucid: this.data.ucid,
        event_id: that.data.id,
        solut: that.data.solut,
        helper: that.data.helper
      }
    }

    console.log('参数：', params)

    util.apiRequest(HandleMemberUpEvent, params).then(r => {
      console.log('提交后：', r)
      if (r.data.code == 1) {
        wx.showModal({
          showCancel: false,
          content: r.data.info,
          success(res) {
            if (res.confirm) {
              wx.redirectTo({
                url: "/pages/grid/griderEventList/griderEventList"
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: r.data.info,
          icon: 'none',
          duration: 2000
        })
      }
    })

  },


  // 上传图片
  chooseImg: function(e) {
    //console.log('选择图片e', e)
    var that = this;
    var imgs = this.data.imgs;
    let uploadFile = ''; //最后处理完，图片上传的图片地址

    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //  console.log('图片', res.tempFilePaths)
        var tempFilePaths = res.tempFilePaths;
        // var imgs = [];
        wx.showLoading({
          title: '上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          let index = that.data.count;
          let canvasId = 'canvasId' + index; // canvas id
          console.log('canvasId', canvasId)
          //获得原始图片大小
          wx.getImageInfo({
            src: tempFilePaths[i],
            success(res) {
              console.log('原始图片r', res)
              var originWidth, originHeight;
              originHeight = res.height;
              originWidth = res.width;
              //压缩比例
              // 最大尺寸限制
              var maxWidth = 800,
                maxHeight = 600;
              // 目标尺寸
              var targetWidth = originWidth,
                targetHeight = originHeight;

              //等比例压缩，如果宽度大于高度，则宽度优先，否则高度优先
              if (originWidth > maxWidth || originHeight > maxHeight) {
                console.log('图片过大需要压缩')
                if (originWidth / originHeight > maxWidth / maxHeight) {
                  // 要求宽度*(原生图片比例)=新图片尺寸
                  targetWidth = maxWidth;
                  targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                } else {
                  targetHeight = maxHeight;
                  targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                }
              }

              //更新canvas大小
              let compressObj = {},
                compressImgsSizeArr = that.data.compressImgsSizeArr;
              compressObj['index'] = index;
              compressObj['cw'] = targetWidth;
              compressObj['ch'] = targetHeight;
              compressImgsSizeArr.push(compressObj)

              that.setData({
                compressImgsSizeArr: compressImgsSizeArr
              });

              //尝试压缩文件，创建 canvas
              var ctx = wx.createCanvasContext(canvasId);
              ctx.clearRect(0, 0, targetWidth, targetHeight);
              ctx.drawImage(tempFilePaths[i], 0, 0, targetWidth, targetHeight);

              //console.log('图片尺寸数组', that.data.compressImgsSizeArr)

              //保存图片
              ctx.draw(false,
                setTimeout(function() {
                  wx.canvasToTempFilePath({
                    canvasId: canvasId,
                    width: targetWidth,
                    height: targetHeight,
                    destWidth: targetWidth,
                    destHeight: targetHeight,
                    quality: 0.4,
                    success: (res) => {
                      console.log('压缩后', res)
                      uploadFile = res.tempFilePath;
                      wx.uploadFile({
                        url: app.globalData.baseURL + '/api/WxProgramApi/upload',
                        filePath: uploadFile,
                        name: 'file',
                        header: {
                          "Content-Type": "multipart/form-data"
                        },
                        formData: {
                          'file': tempFilePaths
                        },
                        success(res) {
                          console.log('图片上传成功', res)
                          let data = JSON.parse(res.data);
                          if (res.statusCode == 200) {
                            var imgSrc = data.data;
                            console.log('图片服务器地址', imgSrc)
                            that.data.imgs.push(imgSrc);
                            console.log('图片数组', imgs)
                            that.setData({
                              imgs: that.data.imgs
                            })
                            wx.hideLoading()
                          }
                        },
                        fail(res) {
                          console.log('上传失败')
                        }
                      })

                    },
                    fail: (err) => {
                      console.error(err)
                    }
                  }, this)
                }, 1000)
              );

            }
          })

          let count = ++that.data.count;
          console.log('++count', count)
          that.setData({
            count: count
          })
          //console.log('循环后count', that.data.count)
        }
      }
    });
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var compressImgsSizeArr = this.data.compressImgsSizeArr;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    compressImgsSizeArr.splice(index, 1);
    this.setData({
      imgs: imgs,
      compressImgsSizeArr: compressImgsSizeArr
    })
  },


  // 预览图片
  previewImg: function(e) {
    let that = this;
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    console.log('预览index', index)
    //所有图片
    var imgType = e.currentTarget.dataset.imgtype;
    var imgs = this.data.imgs;

    console.log('预览时imgs', imgs)
    console.log(imgs[index])
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  }

})